<?php
class News_model extends CI_Model{

	private $NEWS_TABLE = 'news';
	public $archived_news_per_page = 10;
	public $max;

	function __construct(){
		parent::__construct();
		$this->get_total();
	}

	/**
	 * This function gets all the news from the database
	 * */
	function get_news(){
		$this->db->order_by('date', 'desc');
		$this->db->limit(10);
		$query = $this->db->get($this->NEWS_TABLE);

		if ($query->num_rows > 0)
		return $query->result_array();

		return false;

	}

	/**
	 * This function fetches one news story post and returns it.
	 *
	 */
	function get_post($id){
		$this->db->where('id', $id);
		$query = $this->db->get($this->NEWS_TABLE);

		if ($query->num_rows > 0){
			$result = $query->row_array();
			return $result;
		}
	}

	function update_post($news){	
		$this->db->where('id', $news['id']);
		$this->db->update($this->NEWS_TABLE, $news);
		
		if (mysql_error() != ''){
			return mysql_error();
		}
	}


	/**
	 * Inserts new news item into the database
	 * @param data the data array to load into the database
	 * */
	function add_news($data){
		$sql = "INSERT INTO " .$this->NEWS_TABLE ."(content, title, author, date) VALUES (?, ?, ?, now())";
		$bindings = array($data['content'], $data['title'], $data['author']);

		$this->db->query($sql, $bindings);

		if (mysql_error() != ''){
			echo mysql_error() .br(1);
			foreach($bindings as $item){
				echo $item .br(1);
			}

			return false;
		} else {
			return true;
		}
	}

	/**
	 * Fetches the old news using an offset in the database to know which to fetch.
	 * @param $page - Archive page to fetch
	 */
	function get_archives($page){
		$offset = ($page-1)*$this->archived_news_per_page;

		$this->db->order_by('date', 'desc');
		$this->db->limit($this->archived_news_per_page, $offset);
		$query = $this->db->get($this->NEWS_TABLE);

		if ($query->num_rows > 0)
		return $query->result_array();

		return false;

	}

	/**
	 * Gets the maximum number of news
	 */
	function get_total(){
		$this->max = $this->db->count_all($this->NEWS_TABLE);
		return $this->max;
	}
}